package com.common.allCommon;

import java.io.File;
import java.lang.ref.SoftReference;

import android.app.Activity;
import android.os.Environment;

import com.common.android.utils.concurrent.NdCacheAsyncTask;
import com.product.android.business.config.Configuration;
import com.product.android.business.switchUser.SwitchUserReloadManager;
import com.product.android.business.switchUser.SwitchUserReloadManager.TabIdentifier;
import com.product.android.business.switchUser.TabUIRefresh;
import com.product.android.utils.FileHelper;
import com.starappallcommon.R;

public class AllCommonUtils {
	// 主界面的tab页，在恢复可见时检测是否需要重新刷新跟用户相关的界面控件
	public static void tabActivityCheckUserSwitch(Activity activity,
			TabUIRefresh refresh) {
		TabIdentifier id = refresh.getTabIdentifier();
		if (id != null) {
			if (SwitchUserReloadManager.INSTANCE.needReload(id)) { // 需要刷新
				refresh.clearOldAccountUI();
				new RefreshTask(activity).execute(refresh);
			}
		}
	}

	// 切换帐号后用于重新加载数据及刷新界面
	private static class RefreshTask extends
			NdCacheAsyncTask<TabUIRefresh, Void, TabUIRefresh> {

		private final SoftReference<Activity> mRef;

		public RefreshTask(Activity activity) {
			mRef = new SoftReference<Activity>(activity);
		}

		@Override
		protected TabUIRefresh doInBackground(TabUIRefresh... params) {
			TabUIRefresh refresh = params[0];
			refresh.loadDataToMemory(); // 加载数据到内存
			return refresh;
		}

		@Override
		protected void onPostExecute(TabUIRefresh result) {
			SwitchUserReloadManager.INSTANCE.setReloadFlag(
					result.getTabIdentifier(), false); // 清除刷新标志位
			if (mRef == null) {
				return;
			}
			Activity activity = mRef.get();
			if (activity == null) {
				return;
			}
			if (activity.isFinishing()) {
				return;
			}
			result.refreshWhenSwitchUser(); // 刷新界面
		}

	}
	
	/**
	 * 获取临时存放目录
	 * 
	 * @return
	 */
	public static int getTempPath(StringBuilder sbPath) {
		return getNotePath(Configuration.TempDir, sbPath);
	}

	/**
	 * 
	 * @param dir
	 *            目录类型
	 * @param sbPath
	 *            返回路径
	 * @return
	 */
	private static int getNotePath(String dir, StringBuilder sbPath) {
		int ireturn = R.string.sdcard_not_found;
		try {
			sbPath.delete(0, sbPath.length());
			if (Environment.getExternalStorageState().equals(
					Environment.MEDIA_MOUNTED)) {
				String sdcardpath = Environment.getExternalStorageDirectory()
						.getAbsolutePath();
				sbPath.append(sdcardpath).append(Configuration.separatorChar)
						.append(Configuration.PATH);

				File noteDir = new File(sbPath.toString());
				if (!noteDir.exists())
					noteDir.mkdir();
				sbPath.append(Configuration.separatorChar).append(dir);
				sbPath.append(Configuration.separatorChar);
				noteDir = new File(sbPath.toString());
				if (!noteDir.exists()) {
					noteDir.mkdir();
					FileHelper.createNomedia(sbPath);
				}
				ireturn = 0;
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return ireturn;
	}
}
